import lioncen.cti.jmsi.*;
import lioncen.cti.jmsi.object.*;
import lioncen.cti.jmsi.engine.*;
import javax.servlet.http.Cookie
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import cn.umum.msi.listener.MSIAdapter;
import cn.umum.msi.User;
class LoginController {
    static def allowedMethods = [setDN:'POST', dialOut:'POST', login:'POST']
    
    
    def index = {
        flash.message = flash.message;
        redirect(action: 'form')
    }
    def logout={
        public static MSI msi = null;
        msi = servletContext.getAttribute("msi"+cookie(name:"MSI-JSESSIONID"));
        if(msi==null){
            flash.message = "操作失败，登录已过期或还未登录，请重新登录"
            redirect(uri: "/login");
        }
        private int agentID;
        agentID=0;
        if(cookie(name:"agentID")!=null){
            agentID=Integer.valueOf(cookie(name:"agentID"));
        }
        int ret=-1;
        String logoutmsg="暂未退出";
        boolean islogout=0;
        int i=0;
        ret = msi.logout(agentID);
        if (ret==0){
            islogout=1;
            logoutmsg="登出成功";
            user=users.remove("A"+agentID);
            if(user==null){
                println("-------user A"+agentID+" not exit--------");
            }
            else{
                println("-------delete A"+agentID+" successed--------");
            }
            flash.message = "退出成功，如需重新登录，请重新输入座席信息"
            redirect(uri: "/login");
        }
        else{
            flash.message = "操作失败，登录已过期或还未登录，请重新登录"
            redirect(uri: "/login");
        }
            
        
    }
    def setbusy={
        public static MSI msi = null;
        msi = servletContext.getAttribute("msi"+cookie(name:"MSI-JSESSIONID"));
        if(msi==null){
            flash.message = "操作失败，登录已过期或还未登录，请重新登录"
            redirect(uri: "/login");
        }
        private int agentID;
        agentID=0;
        if(cookie(name:"agentID")!=null){
            agentID=Integer.valueOf(cookie(name:"agentID"));
        }
        int ret=-1;
        MsiInfo msiinfo = MsiInfo.findByAgentID(agentID)
        if(msiinfo){
            println("msiagentDN="+msiinfo.agentDN);
            msiinfo.agtAction="BUSY";
            msiinfo.status="AS_OK";
            msiinfo.save();
        }
        ret = msi.setAgentStatus(3);
        if (ret==0){
            user = new User();
            user.setUserid("A"+agentID);
            user.setUsername("username"+agentID);
            user.setagentDN(msiinfo.agentDN);
            user.setUserStat(3);
            users.put("A"+agentID,user);
            MSIAdapter.agentStatsChange.put("A"+agentID,user);
            flash.message = "忙置成功"
            redirect(uri: "/msi/userinfo");
        }else{
            flash.message = "操作失败，登录已过期或还未登录，请重新登录"
            redirect(uri: "/login");
        }
        
    }
    def setidle={
        public static MSI msi = null;
        msi = servletContext.getAttribute("msi"+cookie(name:"MSI-JSESSIONID"));
        if(msi==null){
            flash.message = "操作失败，登录已过期或还未登录，请重新登录"
            redirect(uri: "/login");
        }
        private int agentID;
        agentID=0;
        if(cookie(name:"agentID")!=null){
            agentID=Integer.valueOf(cookie(name:"agentID"));
        }
        int ret=-1;
        MsiInfo msiinfo = MsiInfo.findByAgentID(agentID)
        if(msiinfo){
            msiinfo.agtAction="WORK";
            msiinfo.status="AS_OK";
            msiinfo.save();
        }
        ret = msi.setAgentStatus(2);
        if (ret==0){
            user = new User();
            user.setUserid("A"+agentID);
            user.setUsername("username"+agentID);
            user.setagentDN(msiinfo.agentDN);
            user.setUserStat(2);
            users.put("A"+agentID,user);
            MSIAdapter.agentStatsChange.put("A"+agentID,user);
            flash.message = "闲置成功"
            redirect(uri: "/msi/userinfo");
        }else{
            flash.message = "操作失败，登录已过期或还未登录，请重新登录"
            redirect(uri: "/login");
        }
    }
    def setDND={
        if(params.id==null){
            render "error";
        }
        int mode = Integer.valueOf(params.id)
        public static MSI msi = null;
        msi = servletContext.getAttribute("msi"+cookie(name:"MSI-JSESSIONID"));
        if(msi==null){
            flash.message = "操作失败，登录已过期或还未登录，请重新登录"
            redirect(uri: "/login");
        }
        private int agentID;
        agentID=0;
        if(cookie(name:"agentID")!=null){
            agentID=Integer.valueOf(cookie(name:"agentID"));
        }
        int ret=-1;
        MsiInfo msiinfo = MsiInfo.findByAgentID(agentID)
        if(msiinfo){
            msiinfo.agtAction="WORK";
            msiinfo.status="AS_OK";
            msiinfo.save();
        }
        ret=msi.setDND(mode);
        if(ret==0){
            flash.message = "setDND"+mode+"成功"
            redirect(uri: "/msi/userinfo");
        }else{
            flash.message = "操作失败，登录已过期或还未登录，请重新登录"
            redirect(uri: "/login");
        }
        
    }
    def addAcd = {DialOutCommand cmd ->
        if (cmd.hasErrors()) {
            flash.message = "电话号码输入错误，请重新输入"
            redirect(action: 'acdform')
        } else {
            public static MSI msi = null;
            msi = servletContext.getAttribute("msi"+cookie(name:"MSI-JSESSIONID"));
            if(msi==null){
                flash.message = "操作失败，登录已过期或还未登录，请重新登录"
                redirect(uri: "/login");
            }
            private int agentID;
            agentID=0;
            if(cookie(name:"agentID")!=null){
                agentID=Integer.valueOf(cookie(name:"agentID"));
            }
            int ret=-1;
            MsiInfo msiinfo = MsiInfo.findByAgentID(agentID)
            String loginmsg;
            boolean islogin=0;
            int i=0;
            //ret=msi.dialout(msiinfo.agentDN, -1, "", false);
            String cmdStr;
            cmdStr="2007;1;xms;-1;1;100;2001";
            Vector monitorItemList = new Vector();
            ret = msi.invokeMonitorCmd(99, 3042, 1, cmdStr, monitorItemList);
            //.invokeMonitorCmd(99, 3042, 1, "2007;1;xms;-1;1;100;2001", Vector monitorItemList);
            if (ret==0){
                islogin=1;
                loginmsg="successed";
                

            }
            else{
                loginmsg="dialout failed";
            }
            render loginmsg+msi.getLastErrorString();
        }
    }
    def setCallProtect={
        if(params.id==null){
            render "error";
        }
        int mode = Integer.valueOf(params.id)
        public static MSI msi = null;
        msi = servletContext.getAttribute("msi"+cookie(name:"MSI-JSESSIONID"));
        if(msi==null){
            flash.message = "操作失败，登录已过期或还未登录，请重新登录"
            redirect(uri: "/login");
        }
        private int agentID;
        agentID=0;
        if(cookie(name:"agentID")!=null){
            agentID=Integer.valueOf(cookie(name:"agentID"));
        }
        int ret=-1;
        MsiInfo msiinfo = MsiInfo.findByAgentID(agentID)
        if(msiinfo){
            msiinfo.agtAction="WORK";
            msiinfo.status="AS_OK";
            msiinfo.save();
        }
        ret=msi.setCallProtect(mode);
        if(ret==0){
            flash.message = "setCallProtect"+mode+"成功"
            redirect(uri: "/msi/userinfo");
        }else{
            flash.message = "操作失败，登录已过期或还未登录，请重新登录"
            redirect(uri: "/login");
        }

    }
    def setBusyCallBack={
        if(params.id==null){
            render "error";
        }
        int mode = Integer.valueOf(params.id)
        public static MSI msi = null;
        msi = servletContext.getAttribute("msi"+cookie(name:"MSI-JSESSIONID"));
        if(msi==null){
            flash.message = "操作失败，登录已过期或还未登录，请重新登录"
            redirect(uri: "/login");
        }
        private int agentID;
        agentID=0;
        if(cookie(name:"agentID")!=null){
            agentID=Integer.valueOf(cookie(name:"agentID"));
        }
        int ret=-1;
        MsiInfo msiinfo = MsiInfo.findByAgentID(agentID)
        if(msiinfo){
            msiinfo.agtAction="WORK";
            msiinfo.status="AS_OK";
            msiinfo.save();
        }
        ret=msi.setBusyCallBack(mode);
        if(ret==0){
            flash.message = "setCallProtect"+mode+"成功"
            redirect(uri: "/msi/userinfo");
        }else{
            flash.message = "操作失败，登录已过期或还未登录，请重新登录"
            redirect(uri: "/login");
        }

    }
    //摘机后让主叫保持等待状态
    def hold={
        public static MSI msi = null;
        msi = servletContext.getAttribute("msi"+cookie(name:"MSI-JSESSIONID"));
        if(msi==null){
            flash.message = "操作失败，登录已过期或还未登录，请重新登录"
            redirect(uri: "/login");
        }
        private int agentID;
        agentID=0;
        if(cookie(name:"agentID")!=null){
            agentID=Integer.valueOf(cookie(name:"agentID"));
        }
        int ret = msi.hold();
        if (ret == CTIConst.RET_FAIL)
        {
            println("挂起操作失败:" + msi.getLastErrorString());
        } else
        {
            println("挂起操作成功");
        }
        flash.message = "保持成功"
        redirect(uri: "/msi/userinfo");
    }
    //执行hold后接回操作
    def retrieve={
        public static MSI msi = null;
        msi = servletContext.getAttribute("msi"+cookie(name:"MSI-JSESSIONID"));
        if(msi==null){
            flash.message = "操作失败，登录已过期或还未登录，请重新登录"
            redirect(uri: "/login");
        }
        private int agentID;
        agentID=0;
        if(cookie(name:"agentID")!=null){
            agentID=Integer.valueOf(cookie(name:"agentID"));
        }
        int ret = msi.retrieve();
        if (ret == CTIConst.RET_FAIL)
        {
            println("挂起操作失败:" + msi.getLastErrorString());
        } else
        {
            println("挂起操作成功");
        }
        flash.message = "保持成功"
        redirect(uri: "/msi/userinfo");
    }
    def completeTrans={
        public static MSI msi = null;
        msi = servletContext.getAttribute("msi"+cookie(name:"MSI-JSESSIONID"));
        if(msi==null){
            flash.message = "操作失败，登录已过期或还未登录，请重新登录"
            redirect(uri: "/login");
        }
        private int agentID;
        agentID=0;
        if(cookie(name:"agentID")!=null){
            agentID=Integer.valueOf(cookie(name:"agentID"));
        }
        int ret = msi.transferEx("1003", "", 1, cookie(name:"accdns"));
        if (ret == CTIConst.RET_FAIL)
        {
            println("转移操作失败:" + msi.getLastErrorString());
        } else
        {
            println("转移操作成功");
        }
        flash.message = "转移成功"
        redirect(uri: "/msi/userinfo");
    }
    def transferEx={
        public static MSI msi = null;
        msi = servletContext.getAttribute("msi"+cookie(name:"MSI-JSESSIONID"));
        if(msi==null){
            flash.message = "操作失败，登录已过期或还未登录，请重新登录"
            redirect(uri: "/login");
        }
        private int agentID;
        agentID=0;
        if(cookie(name:"agentID")!=null){
            agentID=Integer.valueOf(cookie(name:"agentID"));
        }
        int ret = msi.completeTrans();
        if (ret == CTIConst.RET_FAIL)
        {
            println("转移操作失败:" + msi.getLastErrorString());
        } else
        {
            println("转移操作成功");
        }
        flash.message = "转移成功"
        redirect(uri: "/msi/userinfo");
    }

    def initTrans={
        public static MSI msi = null;
        msi = servletContext.getAttribute("msi"+cookie(name:"MSI-JSESSIONID"));
        private int agentID;
        agentID=0;
        if(cookie(name:"agentID")!=null){
            agentID=Integer.valueOf(cookie(name:"agentID"));
        }
        int ret = msi.initTrans("1003", "", false);
        if (ret == CTIConst.RET_FAIL)
        {
            println("转移操作失败:" + msi.getLastErrorString());
        } else
        {
            println("转移操作成功");
        }
        flash.message = "转移成功"
        redirect(uri: "/msi/userinfo");
    }
    def setConn = {
        if(params.id==null){
            render "error";
        }
        public static MSI msi = null;
        msi = new MSI();
        msi.ctiEventListener = new MSIAdapter();
        private String agentDN,ctiIP,accdns;
        private int agentID, ctiPort;
        private boolean	isMonitor,isSilentMode
        ctiIP = "127.0.0.1";
        ctiPort = 10089;
        msi.setConnInfo(ctiIP,ctiPort);
        //msi.setDN(agentDN);
        msi.start();
        //params.id
        Cookie namecookie = new Cookie("MSI-JSESSIONID",cookie(name:'JSESSIONID'))
        namecookie.setMaxAge(60*60*24*30);
        namecookie.setPath("/msi/");
        response.addCookie(namecookie)
        servletContext.setAttribute("msi"+cookie(name:"JSESSIONID"),msi)
        flash.message = "连接msi成功"
        redirect(action: 'form')
    }
    def dialOut = {DialOutCommand cmd ->
        if (cmd.hasErrors()) {
            flash.message = "电话号码输入错误，请重新输入"
            redirect(action: 'dialoutform')
        } else {
            public static MSI msi = null;
            msi = servletContext.getAttribute("msi"+cookie(name:"MSI-JSESSIONID"));
            if(msi==null){
                flash.message = "操作失败，登录已过期或还未登录，请重新登录"
                redirect(uri: "/login");
            }
            private int agentID;
            agentID=0;
            if(cookie(name:"agentID")!=null){
                agentID=Integer.valueOf(cookie(name:"agentID"));
            }
            println agentID;
            int ret=-1;
            MsiInfo msiinfo = MsiInfo.findByAgentID(agentID)
            String loginmsg;
            boolean islogin=0;
            int i=0;
            ret=msi.dialout(msiinfo.agentDN, -1, "", false);
            if (ret==0){
                islogin=1;
                loginmsg="successed";
                int iRet=-1;
                iRet=msi.dialout(cmd.agentDN, -1, "", false);
                if (iRet==0){
                    render "dailout successed";
                }
                else{
                    render "dialout failed";
                }

            }
            else{
                loginmsg="dialout failed";
            }
            render loginmsg;
        }
    }
    def setDN = {DialOutCommand cmd ->
        //render request.form["relogin"]
        //render request.getParameter("relogin")
        public static MSI msi = null;
        msi = servletContext.getAttribute("msi"+cookie(name:"MSI-JSESSIONID"));
        //msi.ctiEventListener = new MyMSIEventHandler();
        private int agentID;
        if (cmd.hasErrors()) {
            flash.message = "电话号码输入错误，请重新输入"+request.getParameter("relogin")
            redirect(action: 'setdnform')
        } else {
            agentID=0;
            if(cookie(name:"agentID")!=null){
                agentID=Integer.valueOf(cookie(name:"agentID"));
            }
            println agentID;
            int ret=-1;
            MsiInfo msiinfo = MsiInfo.findByAgentID(agentID)
            private String agentDN,ctiIP,accdns;
            private boolean isMonitor,isSilentMode
            String loginmsg;
            boolean islogin=0;
            int i=0;
            if (msiinfo) {
                msi.setDN(cmd.agentDN);
                accdns=msiinfo.accdns;
                isMonitor=0;
                isSilentMode=0;
                if(msiinfo.isMonitor=="true"){
                    isMonitor=1;
                }
                if(msiinfo.isSilent=="true"){
                    isSilentMode=1;
                }
                while(!islogin){
                    msi.logout(agentID);
                    ret=msi.login(agentID, isMonitor, isSilentMode,accdns, "-1", "xms", "");
                    if (ret==0){
                        islogin=1;
                        loginmsg="successed";
                        //MSIAdapter.users;
                        
                    }
                    else{
                        if(i==19)
                        {
                            islogin=1;
                            loginmsg="failed";
                        }
                        i=i+1;
                        println i;
                    }
                }
                switch (loginmsg){
                    case "successed":
                    msiinfo.agentDN=cmd.agentDN;
                    msiinfo.save();
                    Cookie msicookie = new Cookie("agentID",msiinfo.agentID)
                    msicookie.setMaxAge(60*60*24*30);
                    msicookie.setPath("/msi/");
                    response.addCookie(msicookie)
                    Cookie msicookie1 = new Cookie("accdns",msiinfo.accdns)
                    msicookie1.setMaxAge(60*60*24*30);
                    msicookie1.setPath("/msi/");
                    response.addCookie(msicookie1)
                    Cookie msicookie2 = new Cookie("isSilent",Boolean.toString(msiinfo.isSilent))
                    msicookie2.setMaxAge(60*60*24*30);
                    msicookie2.setPath("/msi/");
                    response.addCookie(msicookie2)
                    Cookie msicookie3 = new Cookie("agentDN",msiinfo.agentDN)
                    msicookie3.setMaxAge(60*60*24*30);
                    msicookie3.setPath("/msi/");
                    response.addCookie(msicookie3)
                    //isSilent
                    //render msiinfo.agentID;
                    redirect(uri: "/msi/userinfo/");
                    break;
                    default:
                    render "failed"
                }
                //render loginmsg;
            }
        }
    }
    def joinAcd={JoinAcdCommand cmd ->
        public static MSI msi = null;
        msi = servletContext.getAttribute("msi"+cookie(name:"MSI-JSESSIONID"));
        if(msi==null){
            render "暂未连接cti或cti服务器已关闭";
            redirect(uri: "/login/setConn/"+cookie(name:"agentID"))
        }
        else{
            if (cmd.hasErrors()) {
                flash.message = "登录错误，请重新输入"
                redirect(action: 'joinacdform')
            }
            else {
                //msi.ctiEventListener = new MyMSIEventHandler();
                private String agentDN,accdns;
                private int agentID;
                agentID=Integer.valueOf(cookie(name:"agentID"));
                int ret=msi.joinAcd(agentID, cmd.accdns, 5)
                if (ret == CTIConst.RET_FAIL)
                {
                    println("加入ACD失败:" + msi.getLastErrorString());
                    redirect(uri: "/msi/userinfo/");
                } else
                {
                    println("加入ACD成功,agentID=" + agentID + ",DN=" + agentDN);
                    redirect(uri: "/msi/userinfo/");
                }
            }
        }
    }
    def leaveAcd={JoinAcdCommand cmd ->
        public static MSI msi = null;
        msi = servletContext.getAttribute("msi"+cookie(name:"MSI-JSESSIONID"));
        if(msi==null){
            render "暂未连接cti或cti服务器已关闭";
            redirect(uri: "/login/setConn/"+cookie(name:"agentID"))
        }
        else{
            if (cmd.hasErrors()) {
                flash.message = "登录错误，请重新输入"
                redirect(action: 'joinacdform')
            }
            else {
                //msi.ctiEventListener = new MyMSIEventHandler();
                private String agentDN,accdns;
                private int agentID;
                agentID=Integer.valueOf(cookie(name:"agentID"));
                int ret=msi.leaveAcd(agentID, cmd.accdns)
                if (ret == CTIConst.RET_FAIL)
                {
                    println("离开ACD失败:" + msi.getLastErrorString());
                    redirect(uri: "/msi/userinfo/");
                } else
                {
                    println("离开ACD成功,agentID=" + agentID + ",DN=" + agentDN);
                    redirect(uri: "/msi/userinfo/");
                }
                //render "successed";
            }
        }
    }

    def login = {LoginCommand cmd ->
        public static MSI msi = null;
        msi = servletContext.getAttribute("msi"+cookie(name:"MSI-JSESSIONID"));
        if(msi==null){
            render "暂未连接cti或cti服务器已关闭";
            redirect(uri: "/login/setConn/"+cookie(name:"agentID"))
        }
        else{
            private String agentDN,accdns;
            private int agentID;
            private boolean	isMonitor,isSilentMode
            String loginmsg="登录失败，可能该座席已经登录或者呼叫中心暂时无法连接";
            int ret = CTIConst.RET_FAIL;
            println("Attempting login")
            if (cmd.hasErrors()) {
                flash.message = "登录错误，请重新输入"
                redirect(action: 'form')
            } else {
            
                MsiInfo msiinfo = MsiInfo.findByAgentIDAndPassword(cmd.agentID,cmd.password)
                if (msiinfo) {
                    agentDN=msiinfo.agentDN;
                    msi.setDN(agentDN);
                    agentID=Integer.valueOf(msiinfo.agentID);
                    accdns=msiinfo.accdns;
                    isMonitor=0;
                    isSilentMode=0;
                    if(msiinfo.isMonitor=="true"){
                        isMonitor=1;
                    }
                    if(msiinfo.isSilent=="true"){
                        isSilentMode=1;
                    }
                    boolean islogin=0;
                    int i=0;
                    msi.logout(agentID);
                    ret=msi.login(agentID, isMonitor, isSilentMode,accdns, "-1", "xms", "");
                    if (ret==0){
                        islogin=1;
                        loginmsg="successed";
                        
                    }
                    else{
                        loginmsg="failed";
                    }
                   
            
                    println(loginmsg)
                    switch (loginmsg){
                        case "successed":
                        msiinfo.agtAction="WORK";
                        msiinfo.status="AS_OK";
                        msiinfo.save();
                        user = new User();
                        user.setUserid("A"+agentID);
                        user.setUsername("username"+agentID);
                        user.setagentDN(agentDN);
                        user.setUserStat(2);
                        users.put("A"+agentID,user);
                        MSIAdapter.agentStatsChange.put("A"+agentID,user);
                        
                        Cookie msicookie = new Cookie("agentID",msiinfo.agentID)
                        msicookie.setMaxAge(60*60*24*30);
                        msicookie.setPath("/msi/");
                        response.addCookie(msicookie)
                        Cookie msicookie1 = new Cookie("accdns",msiinfo.accdns)
                        msicookie1.setMaxAge(60*60*24*30);
                        msicookie1.setPath("/msi/");
                        response.addCookie(msicookie1)
                        Cookie msicookie2 = new Cookie("isSilent",Boolean.toString(msiinfo.isSilent))
                        msicookie2.setMaxAge(60*60*24*30);
                        msicookie2.setPath("/msi/");
                        response.addCookie(msicookie2)
                        Cookie msicookie3 = new Cookie("agentDN",msiinfo.agentDN)
                        msicookie3.setMaxAge(60*60*24*30);
                        msicookie3.setPath("/msi/");
                        response.addCookie(msicookie3)
                        redirect(uri: "/msi/userinfo/");
                        break;
                        default:
                        flash.message = "登录失败，可能cti服务器已经关闭"+msi.getLastErrorString();
                        redirect(action: 'form');
                    }
                } else {
                    println("login failed")
                    flash.message = "错误的座席编号或登录密码，请重新输入"
                    redirect(action: 'form')
                }
            }
        }
    }
    def form = {
        public static MSI msi = null;
        msi = servletContext.getAttribute("msi"+cookie(name:"MSI-JSESSIONID"));
        if(msi==null){
            msi = new MSI();
            msi.ctiEventListener = new MSIAdapter();
            private String agentDN,ctiIP,accdns;
            private int agentID, ctiPort;
            private boolean	isMonitor,isSilentMode
            ctiIP = "127.0.0.1";
            ctiPort = 10089;
            msi.setConnInfo(ctiIP,ctiPort);
            msi.start();
            Cookie namecookie = new Cookie("MSI-JSESSIONID",cookie(name:'JSESSIONID'))
            namecookie.setMaxAge(60*60*24*30);
            namecookie.setPath("/msi/");
            response.addCookie(namecookie)
            servletContext.setAttribute("msi"+cookie(name:"JSESSIONID"),msi)
            flash.message = "连接msi成功"
        }
    }
    def dialoutform = {

    }
    def setdnform={
        
    }
    def joinacdform={

    }
    def leaveacdform={

    }
    def acdform={
        
    }

    User user;
    public static Map<String, User> users = MSIAdapter.agentStats;

}

class LoginCommand {

    String agentID
    String agentDN
    String password
    static constraints = {
        agentID(blank:false)
        agentDN(blank:false)
        password(blank:false)
    }
}
class DialOutCommand {
    String agentDN
    static constraints = {
        agentDN(blank:false)
    }

}
class JoinAcdCommand{
    String accdns
    static contraints={
        accdns(blank:false)
    }
}


